package com.ruoyi.common.utils;

import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.binary.Base64;

// CryptoJS前端加密后台Java解密
public class DesCipherUtil {

    private static final String accessKeySecret = "ganluhua@123456!";

    /**
     * AES解密
     *
     * @param encryptStr 密文
     * @return 明文
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr) throws Exception {
        if (StringUtils.isEmpty(encryptStr)) {
            return null;
        }

        byte[] encryptByte = Base64.decodeBase64(encryptStr);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(accessKeySecret.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptByte);
        return new String(decryptBytes);
    }

    /**
     * AES加密
     *
     * @param content    明文
     * @return 密文
     * @throws Exception
     */
    public static String aesEncrypt(String content) throws Exception {
        if (StringUtils.isEmpty(content)) {
            return null;
        }

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(accessKeySecret.getBytes(), "AES"));

        byte[] encryptStr = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(encryptStr);
    }

    // 测试加密与解密
    // public static void main(String[] args) {
    // try {
    // String secretKey = "aaaabbbbccccdddd";
    // String content = "{ a: 1, b: 2}";
    // String s1 = aesEncrypt(content, secretKey);
    // System.out.println(s1);
    // String s = aesDecrypt(s1, secretKey);
    // System.out.println(s);
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
}